package com.yingpai.fitness.dvp_2_0.main.fragment.mine.assmble;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.lzy.okgo.model.Response;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.yingpai.fitness.R;
import com.yingpai.fitness.dvp_2_0.common.adapter.BaseAdapterHelper;
import com.yingpai.fitness.dvp_2_0.common.adapter.QuickAdapter;
import com.yingpai.fitness.dvp_2_0.common.finalokgo.callback.Callback;
import com.yingpai.fitness.dvp_2_0.common.finalokgo.request.RequestType;
import com.yingpai.fitness.dvp_2_0.common.fragment.CommonFragment;
import com.yingpai.fitness.dvp_2_0.common.util.GsonUtil;
import com.yingpai.fitness.dvp_2_0.common.util.constant.Contacts;
import com.yingpai.fitness.dvp_2_0.common.view.XListView;
import com.yingpai.fitness.dvp_2_0.main.activity.mine.LogisticsActivity;
import com.yingpai.fitness.dvp_2_0.main.activity.mine.assmble.AssmbleCommentActivity;
import com.yingpai.fitness.dvp_2_0.main.activity.mine.assmble.AssmbleRefundServiceActivity;
import com.yingpai.fitness.dvp_2_0.main.activity.shop.assmble.AssmbleOrderActivity;
import com.yingpai.fitness.dvp_2_0.main.activity.shop.assmble.AssmbleShopDetailActivity;
import com.yingpai.fitness.dvp_2_0.main.bean.CommentListBean;
import com.yingpai.fitness.dvp_2_0.main.bean.assmble.AssmbleDetailBean;
import com.yingpai.fitness.dvp_2_0.main.bean.assmble.AssmbleOrderListBean;
import com.yingpai.fitness.dvp_2_0.main.util.ToastUtil;
import com.yingpai.fitness.dvp_2_0.main.util.constant.Constant;
import com.yingpai.fitness.dvp_2_0.main.util.constant.Url;
import com.yingpai.fitness.dvp_2_0.main.widget.round.RCRelativeLayout;
import com.yingpai.fitness.entity.ShopDetailMcipChildBean;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by ASUS on 2018/11/23.
 */

public class AssmbeSuccessOrderFragment extends CommonFragment implements OnRefreshLoadMoreListener {

    @BindView(R.id.listview)
    ListView listView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.empty)
    LinearLayout empty;
    @BindView(R.id.title_bar)
    RelativeLayout title_bar;
    Unbinder unbinder;
    private String status;
    private QuickAdapter<AssmbleOrderListBean.DataBean.PageInfoBean.ListBeanX> quickAdapter;
    private int pageNum = 1;
    private int pageSize = 10;
//    private DecimalFormat df = new DecimalFormat("######.###");

    public static AssmbeSuccessOrderFragment newInstance(String status) {
        AssmbeSuccessOrderFragment orderListFragment = new AssmbeSuccessOrderFragment();
        Bundle bundle = new Bundle();
        bundle.putString("status", status);
        orderListFragment.setArguments(bundle);
        return orderListFragment;
    }

    @Override
    protected View initView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.dvp_2_0_fragment_order_list, container, false);
        unbinder = ButterKnife.bind(this, view);
        title_bar.setVisibility(View.GONE);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        refreshLayout.setOnRefreshLoadMoreListener(this);
        refreshLayout.setRefreshHeader(new MaterialHeader(context).setColorSchemeResources(R.color.common_color));
        status = getArguments().getString("status");

        quickAdapter = new QuickAdapter<AssmbleOrderListBean.DataBean.PageInfoBean.ListBeanX>(context, R.layout.item_order_list) {
            @Override
            protected void convert(final BaseAdapterHelper helper, final AssmbleOrderListBean.DataBean.PageInfoBean.ListBeanX pItem) {
                helper.setText(R.id.title, "订单号：" + pItem.getOrderCode());
                if (pItem.getDetailList() != null && pItem.getDetailList().size() != 0 && pItem.getDetailList().get(0).getList() != null && pItem.getDetailList().get(0).getList().size() != 0) {
                    helper.setText(R.id.shop_count, "共" + pItem.getDetailList().get(0).getList().get(0).getPurchaseAmount() + "件商品");
                }
                helper.setText(R.id.money, "￥" + pItem.getTotalPrice());
                if (pItem.getDetailList() != null && pItem.getDetailList().size() != 0) {
                    helper.setText(R.id.order, pItem.getDetailList().get(0).getBrandName());
                }
                TextView right_tv = helper.getView(R.id.right_tv);
                TextView left_tv = helper.getView(R.id.left_tv);
                TextView center_tv = helper.getView(R.id.center_tv);
                TextView assmble_status = helper.getView(R.id.assmble_status);
                LinearLayout timeLl = helper.getView(R.id.time_ll);
                timeLl.setVisibility(View.GONE);

                assmble_status.setText("拼团成功");
                if (pItem.getStatus() == 1 ) {
                    right_tv.setText("查看详情");
                    center_tv.setText("提醒发货");
                    right_tv.setVisibility(View.VISIBLE);
                    center_tv.setVisibility(View.VISIBLE);
                    left_tv.setVisibility(View.GONE);
                    timeLl.setVisibility(View.GONE);
                    center_tv.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            showToast("提醒成功");
                        }
                    });
                    right_tv.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            showDialog(AssmbeSuccessOrderFragment.this.context, null);
                            HashMap<String, Object> httpParams = new HashMap();
                            httpParams.put("orderId", pItem.getOrderId());
                            finalOkGo.requestEncrypt(RequestType.POSTENCRYPT, Contacts.HOST_SERVER + Url.ASSMBLE_DETAIL_REFRESH, httpParams, Url.ASSMBLE_DETAIL_REFRESH, new Callback<AssmbleDetailBean>() {
                                @Override
                                public void onSuccess(AssmbleDetailBean assmbleDetailBean) {
                                    dismissDialog();
                                    if (assmbleDetailBean.getCode().equals(Constant.REQUEST_SUCCESS_0)) {
                                        Bundle bundle = new Bundle();
                                        bundle.putSerializable("assmbleDetailBean", assmbleDetailBean);
                                        startActivity(AssmbleOrderActivity.class, bundle);
                                    } else {
                                        showToast(assmbleDetailBean.getMessage() + "");
                                    }
                                }

                                @Override
                                public void onError(Response response) {
                                    super.onError(response);
                                    dismissDialog();
                                }

                            });
                        }
                    });
                } else if (pItem.getStatus() == 2) {
                    right_tv.setText("查看详情");
                    center_tv.setText("确认收货");
                    left_tv.setText("查看物流");
                    right_tv.setVisibility(View.VISIBLE);
                    left_tv.setVisibility(View.VISIBLE);
                    center_tv.setVisibility(View.VISIBLE);
                    timeLl.setVisibility(View.GONE);
                    center_tv.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            //确认收货
                            showDialog(AssmbeSuccessOrderFragment.this.context, null);
                            HashMap<String, Object> httpParams = new HashMap();
                            httpParams.put("id", pItem.getOrderId());
                            finalOkGo.requestEncrypt(RequestType.POSTENCRYPT,
                                    Contacts.HOST_SERVER + Url.ASSMBLE_SURE_RECEIVE,
                                    httpParams, Url.ASSMBLE_SURE_RECEIVE, new Callback<CommentListBean>() {
                                        @Override
                                        public void onSuccess(CommentListBean bean) {
                                            dismissDialog();
                                            if(bean.getResult().equals(Constant.REQUEST_SUCCESS)){
                                                onRefresh(refreshLayout);
                                            }else{
                                                ToastUtil.showToast(bean.getMsg());
                                            }
                                        }

                                        @Override
                                        public void onError(Response<String> response) {
                                            super.onError(response);
                                            dismissDialog();
                                        }
                                    });
                        }
                    });
                    left_tv.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Bundle bundle = new Bundle();
                            bundle.putString("com", pItem.getExpressCompanyCode() + "");
                            bundle.putString("num", pItem.getExpressNumber() + "");
                            bundle.putString("state", pItem.getStatus() + "");
                            startActivity(LogisticsActivity.class, bundle);
                        }
                    });
                    right_tv.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            showDialog(AssmbeSuccessOrderFragment.this.context, null);
                            HashMap<String, Object> httpParams = new HashMap();
                            httpParams.put("orderId", pItem.getOrderId());
                            finalOkGo.requestEncrypt(RequestType.POSTENCRYPT, Contacts.HOST_SERVER + Url.ASSMBLE_DETAIL_REFRESH, httpParams, Url.ASSMBLE_DETAIL_REFRESH, new Callback<AssmbleDetailBean>() {
                                @Override
                                public void onSuccess(AssmbleDetailBean assmbleDetailBean) {
                                    dismissDialog();
                                    if (assmbleDetailBean.getCode().equals(Constant.REQUEST_SUCCESS_0)) {
                                        Bundle bundle = new Bundle();
                                        bundle.putSerializable("assmbleDetailBean", assmbleDetailBean);
                                        startActivity(AssmbleOrderActivity.class, bundle);
                                    } else {
                                        showToast(assmbleDetailBean.getMessage() + "");
                                    }
                                }

                                @Override
                                public void onError(Response response) {
                                    super.onError(response);
                                    dismissDialog();
                                }

                            });
                        }
                    });
                } else if (pItem.getStatus() == 3) {
                    right_tv.setText("查看详情");
                    center_tv.setText("评价");
                    right_tv.setVisibility(View.VISIBLE);
                    center_tv.setVisibility(View.VISIBLE);
                    left_tv.setVisibility(View.GONE);
                    timeLl.setVisibility(View.GONE);

                    center_tv.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Bundle bundle = new Bundle();
                            bundle.putSerializable("listBean", pItem);
                            bundle.putString("flag","spell");
                            startActivity(AssmbleCommentActivity.class, bundle);
                        }
                    });
                    right_tv.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            showDialog(AssmbeSuccessOrderFragment.this.context, null);
                            HashMap<String, Object> httpParams = new HashMap();
                            httpParams.put("orderId", pItem.getOrderId());
                            finalOkGo.requestEncrypt(RequestType.POSTENCRYPT, Contacts.HOST_SERVER + Url.ASSMBLE_DETAIL_REFRESH, httpParams, Url.ASSMBLE_DETAIL_REFRESH, new Callback<AssmbleDetailBean>() {
                                @Override
                                public void onSuccess(AssmbleDetailBean assmbleDetailBean) {
                                    dismissDialog();
                                    if (assmbleDetailBean.getCode().equals(Constant.REQUEST_SUCCESS_0)) {
                                        Bundle bundle = new Bundle();
                                        bundle.putSerializable("assmbleDetailBean", assmbleDetailBean);
                                        startActivity(AssmbleOrderActivity.class, bundle);
                                    } else {
                                        showToast(assmbleDetailBean.getMessage() + "");
                                    }
                                }

                                @Override
                                public void onError(Response response) {
                                    super.onError(response);
                                    dismissDialog();
                                }

                            });
                        }
                    });
                } else if (pItem.getStatus() == 4) {
                    right_tv.setVisibility(View.GONE);
                    center_tv.setVisibility(View.GONE);
                    left_tv.setVisibility(View.VISIBLE);
                    timeLl.setVisibility(View.GONE);
                    left_tv.setText("退款退货中");

                    left_tv.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {

                        }
                    });
                } else if (pItem.getStatus() == 6) {
                    right_tv.setVisibility(View.GONE);
                    left_tv.setVisibility(View.VISIBLE);
                    center_tv.setVisibility(View.GONE);
                    timeLl.setVisibility(View.GONE);
                    left_tv.setText("交易关闭");

                    left_tv.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {

                        }
                    });
                } else if(pItem.getStatus() == 7){
                    right_tv.setText("查看详情");
                    left_tv.setText("查看物流");
                    right_tv.setVisibility(View.VISIBLE);
                    left_tv.setVisibility(View.VISIBLE);
                    center_tv.setVisibility(View.GONE);
                    timeLl.setVisibility(View.GONE);
                    left_tv.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Bundle bundle = new Bundle();
                            bundle.putString("com", pItem.getExpressCompanyCode() + "");
                            bundle.putString("num", pItem.getExpressNumber() + "");
                            bundle.putString("state", pItem.getStatus() + "");
                            startActivity(LogisticsActivity.class, bundle);
                        }
                    });
                    right_tv.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            showDialog(AssmbeSuccessOrderFragment.this.context, null);
                            HashMap<String, Object> httpParams = new HashMap();
                            httpParams.put("orderId", pItem.getOrderId());
                            finalOkGo.requestEncrypt(RequestType.POSTENCRYPT, Contacts.HOST_SERVER + Url.ASSMBLE_DETAIL_REFRESH, httpParams, Url.ASSMBLE_DETAIL_REFRESH, new Callback<AssmbleDetailBean>() {
                                @Override
                                public void onSuccess(AssmbleDetailBean assmbleDetailBean) {
                                    dismissDialog();
                                    if (assmbleDetailBean.getCode().equals(Constant.REQUEST_SUCCESS_0)) {
                                        Bundle bundle = new Bundle();
                                        bundle.putSerializable("assmbleDetailBean", assmbleDetailBean);
                                        startActivity(AssmbleOrderActivity.class, bundle);
                                    } else {
                                        showToast(assmbleDetailBean.getMessage() + "");
                                    }
                                }

                                @Override
                                public void onError(Response response) {
                                    super.onError(response);
                                    dismissDialog();
                                }

                            });
                        }
                    });
                }


                XListView child_listview = helper.getView(R.id.child_listview);
                QuickAdapter<AssmbleOrderListBean.DataBean.PageInfoBean.ListBeanX.DetailListBean.ListBean> child_adapter =
                        new QuickAdapter<AssmbleOrderListBean.DataBean.PageInfoBean.ListBeanX.DetailListBean.ListBean>(context, R.layout.item_child_order_list) {
                            @Override
                            protected void convert(BaseAdapterHelper helper, final AssmbleOrderListBean.DataBean.PageInfoBean.ListBeanX.DetailListBean.ListBean cItem1) {
                                helper.getView(R.id.item_rl).setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        Bundle bundle = new Bundle();
                                        bundle.putString("id", cItem1.getMerchandiseId());
                                        startActivity(AssmbleShopDetailActivity.class, bundle);
                                    }
                                });
                                helper.setText(R.id.title, cItem1.getMerchandiseName());
                                helper.setText(R.id.money, "￥" + cItem1.getSinglePrice());
                                List<ShopDetailMcipChildBean> mcipList = GsonUtil.jsonToList(cItem1.getMcipValue(), ShopDetailMcipChildBean.class);
                                StringBuilder stringBuilder = new StringBuilder();
                                for (int i = 0; i < mcipList.size(); i++) {
                                    if (i == mcipList.size() - 1) {
                                        stringBuilder.append(mcipList.get(i).getPropertyValue());
                                    } else {
                                        stringBuilder.append(mcipList.get(i).getPropertyValue() + ";");
                                    }
                                }
                                helper.setText(R.id.num_spec, "数量：x" + cItem1.getPurchaseAmount() + ";" + stringBuilder.toString());
                                RCRelativeLayout rc_layout = helper.getView(R.id.rc_layout);
                                ImageView photo = helper.getView(R.id.photo);
                                Glide.with(AssmbeSuccessOrderFragment.this.context)
                                        .load(cItem1.getPhotoUrl())
                                        .error(R.mipmap.default_small_bg)
                                        .into(photo);
                                rc_layout.setTopLeftRadius(6);
                                rc_layout.setTopRightRadius(6);
                                rc_layout.setBottomLeftRadius(6);
                                rc_layout.setBottomRightRadius(6);

                                TextView return_money_goods = helper.getView(R.id.return_money_goods);
                                if (pItem.getStatus() == 3) {
                                    return_money_goods.setVisibility(View.VISIBLE);
                                    return_money_goods.setText("退货/退款");

                                    return_money_goods.setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            Bundle bundle = new Bundle();
                                            bundle.putString("tag", "退货/退款");
                                            bundle.putString("orderId", pItem.getOrderId());
                                            bundle.putSerializable("DetailListBean", cItem1);
                                            startActivity(AssmbleRefundServiceActivity.class, bundle);
                                        }
                                    });
                                } else if (pItem.getStatus() == 1 ) {
                                    return_money_goods.setVisibility(View.VISIBLE);
                                    return_money_goods.setText("退款");

                                    return_money_goods.setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            Bundle bundle = new Bundle();
                                            bundle.putString("tag", "退款");
                                            bundle.putString("orderId", pItem.getOrderId());
                                            bundle.putSerializable("DetailListBean", cItem1);
                                            startActivity(AssmbleRefundServiceActivity.class, bundle);
                                        }
                                    });
                                } else {
                                    return_money_goods.setVisibility(View.GONE);
                                }
                            }
                        };
                child_listview.setAdapter(child_adapter);
                if (pItem.getDetailList() != null && pItem.getDetailList().size() != 0) {
                    child_adapter.clear();
                    child_adapter.addAll(pItem.getDetailList().get(0).getList());
                    child_adapter.notifyDataSetChanged();
                }
            }
        };

        listView.setAdapter(quickAdapter);

        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    @Subscribe(threadMode = ThreadMode.POSTING)
    public void OnMessageEvent(String s) {
        if (s.equals("20")) {
            pageNum = 1;
            initData();
        } else if (s.equals("updateAssmbleOrderList")) {
            pageNum = 1;
            initData();
        }
    }

    @Override
    protected void initData() {
//        showDialog(context, null);
        HashMap<String, Object> httpParams = new HashMap();
        httpParams.put("status", status);
        httpParams.put("pageNum", pageNum++);
        httpParams.put("pageSize", pageSize);
        finalOkGo.requestEncrypt(RequestType.POSTENCRYPT, Contacts.HOST_SERVER + Url.ASSMBLE_ORDER_LIST, httpParams, Url.ASSMBLE_ORDER_LIST, new Callback<AssmbleOrderListBean>() {
            @Override
            public void onSuccess(AssmbleOrderListBean orderListBean) {
                if (orderListBean.getCode().equals(Constant.REQUEST_SUCCESS_0) && orderListBean.getData() != null && orderListBean.getData().getPageInfo().getList() != null && orderListBean.getData().getPageInfo().getList().size() != 0) {
                    refreshLayout.setNoMoreData(false);
                    if (pageNum - 1 == 1) {
                        quickAdapter.clear();
                        for (int i = 0; i < orderListBean.getData().getPageInfo().getList().size(); i++) {
                            if (orderListBean.getData().getPageInfo().getList().get(i).getGroupStatus().equals("20")) {
                                quickAdapter.add(orderListBean.getData().getPageInfo().getList().get(i));
                            }
                        }
                    } else {
                        for (int i = 0; i < orderListBean.getData().getPageInfo().getList().size(); i++) {
                            if (orderListBean.getData().getPageInfo().getList().get(i).getGroupStatus().equals("20")) {
                                quickAdapter.add(orderListBean.getData().getPageInfo().getList().get(i));
                            }
                        }
                    }
                    if (quickAdapter.getCount() > 0) {
                        empty.setVisibility(View.GONE);
                    } else {
                        empty.setVisibility(View.VISIBLE);
                    }
                } else {
                    if (pageNum - 1 == 1) {
                        quickAdapter.clear();
                        empty.setVisibility(View.VISIBLE);
                    } else {
                        if (quickAdapter.getCount() > 0) {
                            empty.setVisibility(View.GONE);
                        } else {
                            empty.setVisibility(View.VISIBLE);
                        }
                    }
                    refreshLayout.finishLoadMoreWithNoMoreData();
                }

                refreshLayout.finishRefresh();
                refreshLayout.finishLoadMore();
                quickAdapter.notifyDataSetChanged();
//                dismissDialog();
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
//                dismissDialog();
                if (pageNum - 1 == 1) {
                    empty.setVisibility(View.VISIBLE);
                } else {
                    empty.setVisibility(View.GONE);
                }
            }
        });
    }

    @Override
    @OnClick({R.id.empty})
    public void onViewClicked(View view) {
        super.onViewClicked(view);
        switch (view.getId()) {
            case R.id.empty:
                onRefresh(refreshLayout);
                break;
        }
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        initData();
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        pageNum = 1;
        initData();
    }

}
